package com.bookbuf.api.clients;

import com.bookbuf.api.apis.HeWeatherAPI;
import com.bookbuf.api.configurations.IConfiguration;
import com.bookbuf.api.responses.parsers.InternalFactory;
import com.bookbuf.api.responses.parsers.InternalFactoryImpl;
import com.ipudong.core.network.RestServiceFactory;

import java.io.Serializable;

/**
 * 结合 okHttp 请求 向外发起请求;
 * author: robert.
 * date :  16/8/2.
 */
public abstract class ApiClubImpl implements ApiClub, Serializable {

    // 全局配置
    private IConfiguration configuration = null;
    // 解析器工厂
    private InternalFactory factory = null;

    public ApiClubImpl(IConfiguration configuration) {
        this.configuration = configuration;
    }

    protected void updateIConfiguration(IConfiguration configuration) {
        this.configuration = configuration;
    }

    @Override
    public InternalFactory parser() {
        if (this.factory == null) {
            synchronized (this) {
                if (this.factory == null) {
                    this.factory = new InternalFactoryImpl();
                }
            }
        }
        return factory;
    }

    @Override
    public int getAppId() {
        return configuration.getAppId();
    }

    @Override
    public String getAppSecret() {
        return configuration.getAppSecret();
    }

    @Override
    public String getApiServerURL() {
        return configuration.getApiServerURL();
    }

    @Override
    public String getCachePath() {
        return configuration.getCachePath();
    }

    @Override
    public int getCacheSize() {
        return configuration.getCacheSize();
    }

    @Override
    public String getAppVersion() {
        return configuration.getAppVersion();
    }

    @Override
    public String getSessionId() {
        return configuration.getSessionId();
    }

    @Override
    public String getSystemInformation() {
        return configuration.getSystemInformation();
    }

    @Override
    public <T> T api(String baseURL, Class<T> clazz) {
        return RestServiceFactory.getService(baseURL, clazz);
    }

    @Override
    public <T> T api(Class<T> clazz) {
        return api(getApiServerURL(), clazz);
    }


    // http://docs.heweather.com/224489
    protected HeWeatherAPI heWeatherAPI() {
        return api("https://free-api.heweather.com/v5/", HeWeatherAPI.class);
    }

    @Override
    public boolean isMockMode() {
        return configuration.isMockMode();
    }

    @Override
    public void shutdown() {
        configuration = null;
        factory = null;
    }
}
